package xin.nick.rpc.provider.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Nick
 * @date 2021/7/11
 * @description
 */
@Component
@Slf4j
public class ZkProviderRegister implements DisposableBean {

    @Value("${rpc.port}")
    private int port;

    @Value("${rpc.ip}")
    private String ip;

    @Value("${rpc.zk}")
    private String zk;

    private CuratorFramework client;

    public void start() {

        try {
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

            client = CuratorFrameworkFactory.builder()
                    .connectString(zk)
                    .sessionTimeoutMs(50000)
                    .connectionTimeoutMs(30000)
                    .retryPolicy(retryPolicy)
                    .namespace("m-rpc")
                    .build();
            client.start();
            log.info("会话创建");

            String path = "/provider/" + ip + ":" + port;

            if (client.checkExists().forPath(path) != null) {
                client.delete().forPath(path);
            }

            String s = null;
            s = client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL).forPath(path, "0 0".getBytes());

            log.info("创建节点了: " + s);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void destroy() throws Exception {
        String path = "/provider/" + ip + ":" + port;
        client.delete().forPath(path);
    }
}
